package com.minimalist.common.feign.config;


import org.springframework.context.ApplicationEvent;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * Feign 降级事件
 */
public class FeignDegradeEvent extends ApplicationEvent{

    private final String serviceName;
    private final Object params;
    private final String degradeId;
    private final long timeStamp;
    private final Throwable cause;

    // 日期时间格式化器
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    public FeignDegradeEvent(Object source, String serviceName, Object params, String degradeId, Throwable cause){
        super(source);
        this.serviceName = serviceName;
        this.params = params;
        this.degradeId = degradeId;
        this.timeStamp = System.currentTimeMillis();
        this.cause = cause;
    }

    public String getServiceName() {
        return serviceName;
    }

    public Object getParams() {
        return params;
    }

    public String getDegradeId() {
        return degradeId;
    }

    public long getTimeStamp() {
        return timeStamp;
    }

    public Throwable getCause() {
        return cause;
    }

    /**
     * 获取异常原因的简短描述
     */
    public String getCauseMessage(){
        if (cause == null){
            return "未知原因";
        }
        return cause.getClass().getSimpleName() + ": " + cause.getMessage();
    }

    /**
     * 获取格式化后的时间戳
     *
     * @return 格式化后的时间字符串，格式为：yyyy-MM-dd HH:mm:ss.SSS
     */
    public String getFormattedTimestamp(){
        LocalDateTime dateTime = LocalDateTime.ofInstant(
                Instant.ofEpochMilli(timeStamp),
                ZoneId.systemDefault());
        return FORMATTER.format(dateTime);
    }
}